<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新KTT交易处理页面</title>
    <link rel="stylesheet" href="/static/css/ej.css">
    <script src="/static/js/common.js"></script>
</head>
<body>
    {% include "top_bar_ej.html" %}
    
                            <div class="container" style="padding-bottom: 300px;">
    <h2>新KTT交易处理页面</h2>
    
    <div style="margin: 20px 0;">
        <label>
            <input type="checkbox" id="toggleDiv" checked> 显示文件上传区域
        </label>
    </div>

    <div id="uploadSection" style="border: 1px solid #ddd; padding: 20px; margin-bottom: 20px;">
        <h3>文件上传处理</h3>
        <div>
            <p style="font-size:12px;">如果不知道怎么下载快团团上的订单并导出xlsx格式的订单，请<a href="{{url_for('how_to_exp_order')}}">点击这里</a></p>
        </div>
        
        <div style="margin-bottom: 15px;">
            <input type="file" id="xlsxFile" accept=".xlsx" style="display: none;">
            <div><strong>步骤一：</strong><button onclick="document.getElementById('xlsxFile').click()">选择快团团后台下载的XLSX文件</button></div>
            <div style="font-size:12px;">
                <p>要上传处理的文件请命名为（YYYYMMDD-综合-XX.xlsx），</p>
                <p style="color:red;">如：20250701-综合-01.xlsx</p>
            </div>
            <span id="fileName" style="margin-left: 10px;"></span>
        </div>

        <div style="margin-bottom: 15px;">
            <label>序号: </label>
            <select id="seqNoSelect">
                <option value="01">1</option>
                <option value="02">2</option>
                <option value="03">3</option>
                <option value="04">4</option>
                <option value="05">5</option>
                <option value="06">6</option>
                <option value="07">7</option>
                <option value="08">8</option>
                <option value="09">9</option>
                <option value="10">10</option>
            </select>
        </div>
        
        <div><strong>步骤二：</strong><button id="processBtn" style="margin-right: 10px;" disabled>生成给果园的订单</button></div>
        
        <div id="statusArea" style="margin-top: 15px; padding: 10px; border: 1px solid #eee; min-height: 50px;">
            <p>状态: 等待上传文件</p>
        </div>

        <div id="resultStats" style="margin-top: 20px; display: none; padding: 15px; background: #f8f9fa; border-radius: 5px;">
            <h4>订单处理统计</h4>
            <div>总订单数: <span id="totalOrders">0</span></div>
            <div>成功订单: <span id="successOrders">0</span></div>
            <div>失败订单: <span id="failedOrders">0</span></div>
            <div style="margin-top: 10px;">
                <strong>商品分类:</strong>
                <ul id="productsList" style="margin-top: 5px;"></ul>
            </div>
            <div style="margin-top: 10px;">
                <strong><span id="currentDate"></span> 详细统计:</strong>
                <pre id="combinedStats" style="white-space: pre-wrap; margin-top: 5px;"></pre>
            </div>
            <script>
                // 自动设置当前日期
                const today = new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                document.getElementById('currentDate').textContent = `${year}-${month}-${day}`;
            </script>
        </div>
    </div>

    <script>
        const toggleDiv = document.getElementById('toggleDiv');
        const uploadSection = document.getElementById('uploadSection');
        const xlsxFile = document.getElementById('xlsxFile');
        const processBtn = document.getElementById('processBtn');
        const fileName = document.getElementById('fileName');
        const statusArea = document.getElementById('statusArea');

        // 切换显示/隐藏上传区域
        toggleDiv.addEventListener('change', function() {
            uploadSection.style.display = this.checked ? 'block' : 'none';
            // 清空并隐藏统计显示
            document.getElementById('stats-display').style.display = 'none';
            document.getElementById('total-orders').textContent = '0';
            document.getElementById('success-orders').textContent = '0';
            document.getElementById('failed-orders').textContent = '0';
            document.getElementById('products-stats').innerHTML = '';
            document.getElementById('descrpit-display').textContent = '';
            
            // 清空并隐藏数据录入区域
            document.getElementById('sub-forms-container').innerHTML = '';
            document.getElementById('data-entry').style.display = 'none';
        });

        // 文件选择处理
        xlsxFile.addEventListener('change', function() {
            if (this.files.length > 0) {
                fileName.textContent = this.files[0].name;
                processBtn.disabled = false;
                updateStatus('已选择文件: ' + this.files[0].name);
            } else {
                fileName.textContent = '';
                processBtn.disabled = true;
                updateStatus('等待上传文件');
            }
        });

        // 处理按钮点击
        processBtn.addEventListener('click', async function() {
            if (!xlsxFile.files.length) return;
            
            const formData = new FormData();
            formData.append('file', xlsxFile.files[0]);
            formData.append('seq_no', document.getElementById('seqNoSelect').value);
            
            updateStatus('正在处理文件...');
            processBtn.disabled = true;
            
            try {
                const response = await fetch('/new_ktt_deal_xlsx_from_page', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.res === 'ok') {
                    updateStatus('处理成功!');
                    
                    // 显示统计信息（确保显示为整数）
                    document.getElementById('totalOrders').textContent = Math.floor(result.data.total_orders);
                    document.getElementById('successOrders').textContent = Math.floor(result.data.success_orders);
                    document.getElementById('failedOrders').textContent = Math.floor(result.data.failed_orders);
                    
                    // 填充商品分类统计（确保显示为整数）
                    const productsList = document.getElementById('productsList');
                    productsList.innerHTML = '';
                    result.data.products.forEach(product => {
                        const li = document.createElement('li');
                        li.textContent = `${product.name}: ${Math.floor(product.count)}单`;
                        productsList.appendChild(li);
                    });
                    
                    // 填充详细统计（处理数字为整数）
                    let statsText = result.data.combined_stats_text;
                    // 替换所有浮点数为整数
                    statsText = statsText.replace(/(\d+)\.\d+/g, '$1');
                    document.getElementById('combinedStats').textContent = statsText;
                    
                    // 显示统计区域
                    document.getElementById('resultStats').style.display = 'block';
                    
                    // 自动触发下载
                    window.location.href = result.data.download_url;
                } else {
                    updateStatus('处理失败: ' + result.msg);
                }
            } catch (error) {
                updateStatus('请求出错: ' + error.message);
            } finally {
                processBtn.disabled = false;
            }
        });

        function updateStatus(message) {
            statusArea.innerHTML = `<p>状态: ${message}</p>`;
        }
    </script>
                                
                                <!-- Stats display for manual order entry -->
                                <div id="stats-display" style="display:none; margin-top:20px; padding:15px; background:#f8f9fa; border-radius:5px;">
                                    <h4>订单处理统计</h4>
                                    <div>总订单数: <span id="total-orders">0</span></div>
                                    <div>成功订单: <span id="success-orders">0</span></div>
                                    <div>失败订单: <span id="failed-orders">0</span></div>
                                    <div>商品分类统计: 
                                        <ul id="products-stats" style="margin-top:5px;"></ul>
                                    </div>
                                    <div style="margin-top:10px;">
                                        <strong><span id="todayStr"></span> 详细统计:</strong>
                                        <div id="descrpit-display" style="margin-top:5px; white-space:pre-line;"></div>
                                    </div>
                                </div>
        
        <!-- 新增数据录入区域 -->
        <div class="form-section" id="data-entry" style="display:none; margin-top:30px;">
            <h3>新增订单数据</h3>
            <div id="sub-forms-container">
                <!-- 子表单将在这里动态生成 -->
            </div>
            <button id="submit-btn" class="btn btn-primary">提交所有订单</button>
        </div>
    </div>
    
    
    <!-- 固定在底部的选择区域 -->
    <div class="fixed-bottom-section" style="position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 20px; border-top: 1px solid #ddd; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); z-index: 1000;">
        <div class="container">
            <div class="form-group" style="margin-bottom: 20px;">
                <label>序号</label>
                <select id="seq-select" class="form-control">
                    <option value="01" selected>1</option>
                    <option value="02">2</option>
                    <option value="03">3</option>
                    <option value="04">4</option>
                    <option value="05">5</option>
                    <option value="06">6</option>
                    <option value="07">7</option>
                    <option value="08">8</option>
                    <option value="09">9</option>
                    <option value="10">10</option>
                </select>
            </div>
            <div class="form-group" style="margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <label style="margin-bottom: 0;">商品类别</label>
                    <div style="position: relative;">
                        <input type="text" id="category-input" class="form-control" placeholder="输入商品类别名称" style="width:80px; margin-right:15px;">
                        <div id="category-results" style="position: absolute; display:none; max-height:200px; overflow-y:auto; border:1px solid #ddd; margin-top:5px; width:200px; background:white; z-index:100;"></div>
                    </div>
                    <!-- <button class="btn btn-outline-secondary quick-category" data-category="芒果">芒果</button>
                    <button class="btn btn-outline-secondary quick-category" data-category="荔枝">荔枝</button> -->
                </div>
                <select id="category-select" class="form-control" style="display:none">
                    <option value="">请选择商品类别</option>
                </select>
            </div>

            <div class="form-group" id="spec-group" style="display:none; margin-bottom: 20px;">
                <label>商品规格</label>
                <select id="spec-select" class="form-control" style="margin-left:5px;">
                    <option value="">请选择商品规格</option>
                </select>
            </div>

            <div class="info-display" id="info-display" style="display:none; margin-top:20px; padding:15px; background:#f8f9fa; border-radius:5px;">
                <div>
                    <strong>商品编码：</strong>
                    <span id="product-id"></span>
                </div>
                <div style="margin-top:10px;">
                    <strong>发货模板：</strong>
                    <span id="product-template"></span>
                </div>
            </div>
            
            <button id="add-btn" class="btn btn-success" style="margin-top:20px;">增加</button>
        </div>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // 获取所有需要的元素
            const categorySelect = document.getElementById('category-select');
            const categoryInput = document.getElementById('category-input');
            const categoryResults = document.getElementById('category-results');
            const specGroup = document.getElementById('spec-group');
            const specSelect = document.getElementById('spec-select');
            const infoDisplay = document.getElementById('info-display');
            const productIdSpan = document.getElementById('product-id');
            const productTemplateSpan = document.getElementById('product-template');
            const addBtn = document.getElementById('add-btn');
            const dataEntry = document.getElementById('data-entry');
            const submitBtn = document.getElementById('submit-btn');

            // 商品类别搜索功能
            categoryInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                categoryResults.innerHTML = '';
                productIdSpan.textContent = '';
                productTemplateSpan.textContent = '';
                infoDisplay.style.display = 'none';
                
                if(searchTerm) {
                    const matches = Array.from(categorySelect.options).filter(option => 
                        option.value && option.textContent.toLowerCase().includes(searchTerm))
                        .slice(0, 10); // 限制显示10条结果
                    
                    if(matches.length) {
                        matches.forEach(option => {
                            const div = document.createElement('div');
                            div.textContent = option.textContent;
                            div.style.padding = '8px';
                            div.style.cursor = 'pointer';
                            div.addEventListener('click', function() {
                                categoryInput.value = option.textContent;
                                categoryResults.style.display = 'none';
                                // 触发规格更新
                                categorySelect.value = option.value;
                                categorySelect.dispatchEvent(new Event('change'));
                            });
                            categoryResults.appendChild(div);
                        });
                        categoryResults.style.display = 'block';
                    } else {
                        categoryResults.style.display = 'none';
                    }
                } else {
                    categoryResults.style.display = 'none';
                }
            });

            // 点击外部隐藏结果
            document.addEventListener('click', function(e) {
                if(e.target !== categoryInput && !e.target.classList.contains('quick-category')) {
                    categoryResults.style.display = 'none';
                }
            });

            // 快捷类别按钮点击事件
            document.querySelectorAll('.quick-category').forEach(button => {
                button.addEventListener('click', function() {
                    const category = this.dataset.category;
                    categoryInput.value = category;
                    // 查找匹配的option
                    const option = Array.from(categorySelect.options).find(
                        opt => opt.textContent === category
                    );
                    if(option) {
                        categorySelect.value = option.value;
                        categorySelect.dispatchEvent(new Event('change'));
                    }
                });
            });

            // 获取页面配置
            fetch('/get_new_ktt_page_config')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('请求配置失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if(data.res === 'ok') {
                        console.log('config data:',data.data)
                        // 清空现有快捷按钮
                        document.querySelectorAll('.quick-category').forEach(btn => btn.remove());
                        
                        // 填充快捷按钮
                        if(data.data.快捷标签) {
                            data.data.快捷标签.forEach(category => {
                                const btn = document.createElement('button');
                                btn.className = 'btn btn-outline-secondary quick-category';
                                btn.dataset.category = category;
                                btn.textContent = category;
                                btn.style.marginRight='10px';
                                btn.addEventListener('click', function() {
                                    categoryInput.value = category;
                                    const option = Array.from(categorySelect.options).find(
                                        opt => opt.textContent === category
                                    );
                                    if(option) {
                                        categorySelect.value = option.value;
                                        categorySelect.dispatchEvent(new Event('change'));
                                    }
                                });
                                categoryInput.parentNode.insertBefore(btn, categoryInput.nextSibling);
                            });
                        }

                        // 填充一级分类
                        categorySelect.innerHTML = '<option value="">请选择商品类别</option>';
                        Object.keys(data.data.商品).forEach(category => {
                            const option = document.createElement('option');
                            option.value = category;
                            option.textContent = category;
                            categorySelect.appendChild(option);
                        });

                        // 一级分类变化时更新二级规格
                        categorySelect.addEventListener('change', function() {
                            specGroup.style.display = this.value ? 'block' : 'none';
                            specSelect.innerHTML = '<option value="">请选择商品规格</option>';
                            infoDisplay.style.display = 'none';

                            if(this.value) {
                                const subCategories = data.data.商品[this.value];
                                Object.keys(subCategories).forEach(subCat => {
                                    const specs = subCategories[subCat];
                                    Object.keys(specs).forEach(specName => {
                                        const spec = specs[specName];
                                        const option = document.createElement('option');
                                        option.value = specName;
                                        option.textContent = specName;
                                        option.dataset.id = spec.id;
                                        option.dataset.template = spec.template;
                                        specSelect.appendChild(option);
                                    });
                                });
                            }
                        });

                        // 二级规格变化时显示商品信息
                        specSelect.addEventListener('change', function() {
                            if(this.selectedIndex > 0) {
                                const selectedOption = this.options[this.selectedIndex];
                                productIdSpan.textContent = selectedOption.dataset.id;
                                productTemplateSpan.textContent = selectedOption.dataset.template;
                                infoDisplay.style.display = 'block';
                            } else {
                                infoDisplay.style.display = 'none';
                            }
                        });

                        // 增加按钮点击事件
                        addBtn.addEventListener('click', function() {
                            if(!categorySelect.value || !specSelect.value) {
                                alert('请先选择商品类别和规格');
                                return;
                            }

                            const formId = 'form-' + Date.now();
                            const selectedOption = specSelect.options[specSelect.selectedIndex];
                            
                            const formHTML = `
                            <div class="sub-form" id="${formId}" style="margin-bottom: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px;">
                                <div style="margin-bottom: 10px;">
                                    <div><strong>商品类别：</strong>${categorySelect.value}</div>
                                    <div><strong>商品规格：</strong>${specSelect.value}</div>
                                    <div><strong>商品编码：</strong>${selectedOption.dataset.id || ''}</div>
                                    <div><strong>发货模板：</strong>${selectedOption.dataset.template || ''}</div>
                                </div>
                                <div style="margin-top: 15px;">
                                    <div style="margin-bottom: 5px;"><strong>收货信息（每2行一个订单）</strong></div>
                                    <textarea class="form-control addresses-input" rows="6" 
                                        style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;"
                                        placeholder="格式示例：
    订单编号：250720-573822748210053
    收货信息：陈XX 13980808080 广东省深圳市南山区XXX，1
    订单编号：250720-574832723210020
    收货信息：李XX 13969898927 广东省广州市天河区XXX，3"></textarea>
                                </div>
                                <button class="btn btn-danger remove-btn" data-formid="${formId}" 
                                    style="margin-top: 10px;">删除</button>
                            </div>
                            `;

                            document.getElementById('sub-forms-container').insertAdjacentHTML('beforeend', formHTML);
                            dataEntry.style.display = 'block';
                            // 清空并隐藏统计显示
                            document.getElementById('stats-display').style.display = 'none';
                            document.getElementById('total-orders').textContent = '0';
                            document.getElementById('success-orders').textContent = '0';
                            document.getElementById('failed-orders').textContent = '0';
                            document.getElementById('products-stats').innerHTML = '';
                            
                            // 隐藏上传区域并取消勾选
                            document.getElementById('uploadSection').style.display = 'none';
                            document.getElementById('toggleDiv').checked = false;
                        });

                        // 删除子表单
                        document.addEventListener('click', function(e) {
                            if(e.target.classList.contains('remove-btn')) {
                                document.getElementById(e.target.dataset.formid).remove();
                            }
                        });

                        // 提交订单处理
                        submitBtn.addEventListener('click', function() {
                            const subForms = document.querySelectorAll('.sub-form');
                            if(subForms.length === 0) {
                                alert('请至少添加一个订单');
                                return;
                            }

                            const orders = [];
                            subForms.forEach(form => {
                                const addresses = form.querySelector('.addresses-input').value;
                                if(!addresses.trim()) {
                                    alert('请填写收货信息');
                                    return;
                                }

                                const infoDiv = form.querySelector('div > div:nth-child(1)');
                                if (!infoDiv) {
                                    alert('表单结构异常，请重新添加订单');
                                    return;
                                }

                                orders.push({
                                    category: infoDiv.querySelector('div:nth-child(1)').textContent.split('：')[1].trim(),
                                    spec: infoDiv.querySelector('div:nth-child(2)').textContent.split('：')[1].trim(),
                                    product_id: infoDiv.querySelector('div:nth-child(3)').textContent.split('：')[1].trim(),
                                    template: infoDiv.querySelector('div:nth-child(4)').textContent.split('：')[1].trim(),
                                    addresses: addresses
                                });
                            });

                            const seqNo = document.getElementById('seq-select').value;
                            // console.log('seq_no:',seqNo,'orders:',orders);
                            fetch('/deal_submit_ktt_orders', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Accept': 'application/json'
                                },
                                body: JSON.stringify({
                                    seq_no: seqNo,
                                    orders: orders
                                })
                            })
                            .then(response => response.json())
                            .then(data => {
                                if(data.res === 'ok'){
                                    console.log('data response:',data.data);
                                    // 显示统计数据
                                    document.getElementById('total-orders').textContent = data.data.total_orders;
                                    document.getElementById('success-orders').textContent = data.data.success_orders;
                                    document.getElementById('failed-orders').textContent = data.data.failed_orders;
                                    
                                    // 显示商品统计
                                    const productsList = document.getElementById('products-stats');
                                    productsList.innerHTML = '';
                                    data.data.products.forEach(product => {
                                        const li = document.createElement('li');
                                        li.textContent = `${product.name}: ${product.count}单`;
                                        productsList.appendChild(li);
                                    });

                                    // 显示详细统计
                                    const todayStr=document.getElementById('todayStr');
                                    const today=new Date();
                                    const year = today.getFullYear();
                                    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始
                                    const day = String(today.getDate()).padStart(2, '0');

                                    todayStr.textContent=`${year}-${month}-${day}`;
                                    const descrpitDisplay = document.getElementById('descrpit-display');
                                    descrpitDisplay.textContent = '';
                                    if(data.data.combined_stats_text) {
                                        descrpitDisplay.textContent = data.data.combined_stats_text;
                                    } else if(data.data.descrpit) {
                                        data.data.descrpit.forEach(item => {
                                            descrpitDisplay.textContent += `${item.name}: ${item.desc}\n`;
                                        });
                                    }
                                    
                                    document.getElementById('stats-display').style.display = 'block';
                                    document.getElementById('sub-forms-container').innerHTML = '';
                                    dataEntry.style.display = 'none';
                                    
                                    // 自动触发文件下载
                                    if(data.data.download_url) {
                                        window.location.href = data.data.download_url;
                                    }
                                } else {
                                    alert(data.msg || '处理失败');
                                }
                            })
                            .catch(error => {
                                alert('提交失败: ' + error.message);
                            });
                        });
                    } else {
                        alert('获取配置失败');
                    }
                })
                .catch(error => {
                    alert(error.message);
                });
        });
    </script>
</body>
</html>
